<?php 
namespace XFCore\traits\user;
use lib\Examine;
trait InfoTrait{
    public function verifypaypwd()
    {
        // 检查登录状态
        if ($this->islogin_user != 1) {
            exitjson(-1, '请先登录');
        }
    
        // 获取输入的密码
        $inputPassword = trim($this->input->paypass);
        if (empty($inputPassword)) {
            exitjson(-1, '密码不能为空');
        }
        
        // 设置session并返回结果
        if ($this->isValid_PayPwd($inputPassword)) {
            $_SESSION['paypwd'] = aes256auth($this->uid,SYS_KEY);
            exitjson(200, '验证成功');
        }
    
        exitjson(-1, '支付密码错误');
    }
    
    public function edit_userinfo($get , $post , $data){
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }
        $params = array_filter($data, fn($v) => $v !== '');
        if (!empty($params['INPUTFREE']) && !in_array($params['INPUTFREE'], ['3', '4', '5'])) {
            exitjson(-1, '免输模式设置错误');
        }
        if($this->db->update('user',$params,['pid'=>$this->uid])){
            exitjson(200,'修改成功!');
        }
        exitjson(-1,'修改失败！');
    }
    public function create_userrsa(){
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }
        $inputPassword = trim($this->input->paypass);
        if (empty($inputPassword)) {
            exitjson(-1, '密码不能为空');
        }
        if(!$this->isValid_PayPwd($inputPassword)){
            exitjson(-1,'密码错误！');
        }
        
        $privateKey = openssl_pkey_new([
            'private_key_bits' => 2048, // 密钥位数，一般建议使用 2048 位或更高
            'private_key_type' => OPENSSL_KEYTYPE_RSA, // 密钥类型为 RSA
        ]);
        openssl_pkey_export($privateKey, $privateKeyString);
        $publicKey = openssl_pkey_get_details($privateKey)['key'];
        $cleanedKey = trim($publicKey);
        $cleanedKey = str_replace("-----BEGIN PUBLIC KEY-----", "", $cleanedKey);
        $cleanedKey = str_replace("-----END PUBLIC KEY-----", "", $cleanedKey);
        $publicKey = trim($cleanedKey);
        
        $cleanedKey = trim($privateKeyString);
        $cleanedKey = str_replace("-----BEGIN PRIVATE KEY-----", "", $cleanedKey);
        $cleanedKey = str_replace("-----END PRIVATE KEY-----", "", $cleanedKey);
        $privateKeyString = trim($cleanedKey);
        
        if(!empty($privateKeyString) && !empty($publicKey)){
            $params = [
                'rsapublickey'=>$publicKey,
                'rsaprivatekey'=>aes256auth($privateKeyString,SYS_KEY)
            ];
            if($this->db->update('user',$params,['pid'=>$this->uid])){
                exitjson(200,'生成成功',['rsaprivatekey'=>$privateKeyString]);
            }
        }
        exitjson(-1,'生成失败');
    }
    public function resetKey(){
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }
        $key =  md5('1'.mt_rand(10000000,99999999).$this->userrow['qq']);
        if($this->db->update('user',['key'=>$key],['pid'=>$this->uid])){
            exitjson(200,'重置成功！');
        }
        exitjson(-1,'重置失败！');
    }
    public function verify_captcha(){
        if($this->islogin_user != 1) {
            exitjson(-1,'请先登录');
        }
        
        if($this->XFCaptcha->XYcaptcha($this->input->captcha)){
            exitjson(200,'success');
        }
        exitjson(-1,'fail');
    }
    public function send_verify_code($get , $data){
        if($this->islogin_user != 1) {
            exitjson(-1,'请先登录');
        }
        unset($data['captcha']);
        if(!$this->XFCaptcha->XYcaptcha($this->input->captcha)){
            exitjson(-1,'验证码为空或错误！');
        }
        Examine::checkRequiredParams($data);
        $type  = $data['type'];
        $value = $data['value'];
        $userrow = $this->userrow;
        
        if($type == 'email' || $type == 'phone'){
            $zh = $type == 'email'?"邮箱":'手机号';
            if($this->db->userrow($value,$type,"pid")){
                exitjson(-1,'该'.$zh.'已被别的账户绑定或未修改');
            }
        }else{
            if($this->conf->verifytype == 'email' && empty($userrow['email'])){
                exitjson(-1,'未绑定邮箱');
            }
            if($this->conf->verifytype == 'phone' && empty($userrow['phone'])){
                exitjson(-1,'未绑定手机号');
            }
            $type = $this->conf->verifytype;
            $value = $userrow[$type];
        }
        
        if($type == 'phone'){
            $phone = preg_replace('/\D/', '', $value);
            if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                exitjson(500, "手机号格式不正确");
            }
            $to = !empty($userrow['phone']) ? $userrow['phone'] : $value;
        }else{
            if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                exitjson(500, "邮箱格式不正确");
            }
            $to = !empty($userrow['email']) ? $userrow['email'] : $value;
        }
        
        $row = $this->db->select('regcode', '*', ['to' => $to], [
            'orderBy' => 'id DESC',
            'limit' => 1,
            'single_row' => true
        ],['single_row'=>true])['result'];
        if($row && $row['time'] > time() - 60){
            exitjson(-1, "两次发送短信之间需要相隔60秒！");
        }
        
        $count = $this->db->select('regcode', 'COUNT(*) as count', [
            'to' => $to,
            'time' => ['operator' => 'gt', 'value' => time() - 3600 * 24]
        ])['result']['count'];
        if ($count > 6) {
            exitjson(-1, "发送次数过多，请更换收信方式！");
        }
        $count = $this->db->select('regcode', 'COUNT(*) as count', [
            'ip' => http_ip(),
            'time' => ['operator' => 'gt', 'value' => time() - 3600 * 24]
        ],['single_row'=>true])['result']['count'];
        if ($count > 10) {
            exitjson(-1, "你今天发送次数过多，已被禁止发信");
        }
        $code = rand(111111, 999999);
        $sms_auth = false;
        if($type == 'phone'){
            $json = json_decode(send_sms($to, $code, 'univer'), true);
            $sms_auth = ($json['code'] == 200);
        }else{
            $sub = $this->conf['sitename'] . ' - 验证码获取';
            $msg = $this->MsgNotice->send('code',$userrow['user'],['code'=>$code]);
            $sms_auth = send_mail($to, $sub, $msg);
        }
        if($sms_auth){
            $insertData = [
                'type' => '2',
                'code' => $code,
                'to' => $to,
                'time' => time(),
                'ip' => http_ip(),
                'status' => '0'
            ];
            if ($this->db->insert('regcode', $insertData)) {
                
                $_SESSION['send_mail'] = time();
                exitjson(200, "验证码发送成功");
            } else {
                exitjson(-1, "验证码写入失败");
            }
        }
        exitjson(-1, "验证码发送失败");
    }
    
    public function update_contact($get , $data){
        if($this->islogin_user != 1) {
            exitjson(-1,'请先登录');
        }
        unset($data['captcha']);
        if(!$this->XFCaptcha->XYcaptcha($this->input->captcha)){
            exitjson(-1,'验证码为空或错误！');
        }
        Examine::checkRequiredParams($data);
        $type = $data['type'];
        $value = $data['newvalue'];
        $code  = $data['verify_code'];
        $userrow = $this->userrow;
        
        
        $params = [];
        if($type =='phone' || $type == 'email'){
            if($type == 'phone'){
                $phone = preg_replace('/\D/', '', $value);
                if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                    exitjson(500, "手机号格式不正确");
                }
                $to = !empty($userrow['phone']) ? $userrow['phone'] : $value;
            }else{
                if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                    exitjson(500, "邮箱格式不正确");
                }
                $to = !empty($userrow['email']) ? $userrow['email'] : $value;
            }
        }else{
            $to = $userrow[$this->conf->verifytype];
           
            if($type == 'pass'){
                if(strlen($value) < 6){
                    exitjson(500, "密码长度不能少于6位");
                }
                if(ctype_digit($value)){
                    exitjson(500, "密码过于简单，请使用包含字母、数字和特殊字符的更复杂密码");
                }
                $salt  = $this->salt;
                $value =  md5($salt . md5($salt.$value.$salt.md5($salt.$value.$salt).$value.$salt) . $salt);
                $params['salt'] = $this->salt;
            }else{
                $value = md5(md5($value));
            }
        }
        $params[$type] = $value;
        
        $result = $this->db->select('regcode', '*', [
            'to' => $to,
            'code' => $code,
            'type' => 2
        ], [
            'orderBy' => 'id DESC',
            'limit' => 1,
            'single_row' => true
        ])['result'];
        if(!$result)exitjson(-1,'验证码不正确！');
        if($result['time']<time()-300 || $result['status']==1)exitjson(-1,'验证码已失效，请重新获取!');
        $updateResult = $this->db->update('user', 
            $params, 
            ['pid' => $this->uid]
        );
        if($updateResult){
            // 更新验证码状态
            $this->db->update('regcode', 
                ['status' => '1'], 
                ['id' => $result['id']]
            );
            createLog('修改联系方式成功', http_ip() , $this->userrow['user']);
            exitjson(200,'修改成功！');
        }
        exitjson(-1,'修改失败！');
    }
    protected function isValid_PayPwd($inputPassword){
        // 验证密码
        $isValid = false;
        if (empty($this->userrow['pay_pass'])) {
            // 使用登录密码验证
            $salt = $this->userrow['salt'];
            $hashedPassword = md5($salt . md5($salt.$inputPassword.$salt.md5($salt.$inputPassword.$salt).$inputPassword.$salt) . $salt);
            $isValid = hash_equals($hashedPassword, $this->userrow['pass']);
        } else {
            // 使用支付密码验证
            $hashedPassword = md5(md5($inputPassword));
            $isValid = hash_equals($hashedPassword, $this->userrow['pay_pass']);
        }
        return $isValid; 
    }
    
}
?>